//#ifdef H5
import {
	getWechatConfig,
	wechatAuthH5,
	alipayAuth,
	systemConfig
} from "@/api/public.js";
var jweixin = require('jweixin-module');
let instance;
//#endif
import {
	channelBindSeller
} from "@/api/merchant.js"

export default {
	// ***********************************微信相关********************************************
	//判断是否在微信中  
	isWechat() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			return true;
		} else {}
	},
	wechat(jsConfig, callback) {
		return new Promise((resolve, reject) => {
			if (instance) return resolve(instance);
			getWechatConfig().then(res => {
				jweixin.config({
					debug: res.data.debug,
					appId: res.data.appId,
					timestamp: res.data.timestamp,
					nonceStr: res.data.nonceStr,
					signature: res.data.signature,
					jsApiList: res.data.jsApiList
				});
				instance = res.data;
				resolve(instance);
			})
		});
	},
	scanQRCode() {
		this.wechat().then(res => {
			jweixin.ready(function() {
				jweixin.scanQRCode({
					needResult: 0, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
					scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
					success: function(res) {
						var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
					}
				})
			})
		})
	},
	getLocation() {
		return new Promise((resolve, reject) => {
			this.wechat().then(res => {
				jweixin.ready(function() {
					jweixin.getLocation({
						type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: function(res) {
							resolve(res);
						},
						fail: function(err) {
							console.log('dizhierr', err)
						}
					});
				})
			})
		});

	},
	pay(jsConfig, url, cancelGo, cancelBack, callBack) {
		this.wechat().then(res => {
			jweixin.ready(function() {
				jweixin.chooseWXPay({
					timestamp: jsConfig.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					nonceStr: jsConfig.nonceStr, // 支付签名随机串，不长于 32 位
					package: jsConfig.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
					signType: jsConfig.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
					paySign: jsConfig.paySign, // 支付签名
					success(res) {
						if(url) {
							uni.redirectTo({
								url: url
							})
						} else {
							callBack
						}
						
					},
					fail(res) {},
					cancel(res) {
						if (cancelGo) {
							uni.redirectTo({
								url: url
							})
						} else if (cancelBack) {
							uni.navigateBack({

							})
						} else {}
					}
				});
			})
		});
	},
	share(title, desc, link, imgurl) {
		this.wechat().then(res => {
			jweixin.ready(function() { //需在用户可能点击分享按钮前就先调用
				jweixin.updateAppMessageShareData({
					title: title, // 分享标题
					desc: desc, // 分享描述
					link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: imgurl, // 分享图标
					success: function() {
						// 设置成功
					}
				})
			});
		});
	},
	wxLogin() {
		this.wechat().then(res => {
			location.href = this.getAuthUrl(res.appId);
		});
	},
	getAuthUrl(appId) {
		const redirect_uri = encodeURIComponent(location.origin + "/pages/login/loading");
		const state = encodeURIComponent(("" + Math.random()).split(".")[1] + "authorizestate")
		return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appId + '&redirect_uri=' + redirect_uri +
			'&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect';
	},
	auth(code) {
		wechatAuthH5({
			spread: uni.getStorageSync("pid"),
			pos: uni.getStorageSync("pos"),
			login_type: "",
			code: code
		}).then(res => {
			this.loginDeal(res, "H5")
		})
	},
	// ***********************************微信相关结束******************************************


	// ***********************************支付宝相关********************************************
	//支付宝登录
	alipayLogin() {
		uni.showLoading({
			mask:true
		})
		systemConfig({ //联系电话
			filed: 'alipay_wp_app_id'
		}).then(res => {
			uni.hideLoading()
			const appId = res.msg
			const redirect_uri = encodeURIComponent(location.origin + "/pages/login/loading");
			location.href =
				'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' + appId + '&scope=auth_user&redirect_uri=' +
				redirect_uri + '&state=ini'
		})
	},
	alipayAuth(code) {
		alipayAuth({
			spread: uni.getStorageSync("pid"),
			pos: uni.getStorageSync("pos"),
			auth_code: code
		}).then(res => {
			this.loginDeal(res, "ali_app")
		})
	},
	// ***********************************支付宝相关结束********************************************
	//登录成功之后
	loginDeal(res, userType) {
		uni.hideLoading()
		uni.setStorageSync('Authori-zation', res.data.token)
		uni.setStorageSync('expires_time', res.data.expires_time);
		uni.setStorageSync("userInfo", res.data.userInfo)
		let kind = res.data.userInfo.user_kind
		if ([1, 2, 3, 4, 5, 6].includes(Number(kind)) && [4, 5].includes(Number(uni.getStorageSync('pos')))) {
			let content = ""
			if (kind == 1) {
				content = "您已入驻过商户"
			} else if (kind == 2) {
				content = "您已是代理商，不能入驻商户"
			} else if (kind == 3) {
				content = "您已是渠道商，不能入驻商户"
			} else if (kind == 4) {
				content = "您已是地推人员，不能入驻商户"
			} else if (kind == 5) {
				content = "您已是运营中心，不能入驻商户"
			} else if (kind == 6) {
				content = "您已是技术部，不能入驻商户"
			}
			uni.showModal({
				content: content,
				showCancel: false,
				success() {
					uni.removeStorageSync("pid")
					uni.removeStorageSync("pos")
					uni.redirectTo({
						url: "/pages/index/index?current=0"
					})
				}
			})
		} else {
			uni.showToast({
				title: "登录成功"
			})
			uni.removeStorageSync("pid")
			if ([4, 5].includes(Number(uni.getStorageSync('pos')))) {
				uni.setStorageSync("back", true)
			} else if ([1].includes(Number(uni.getStorageSync('pos')))) {
				uni.setStorageSync("isPerson",true)
				uni.removeStorageSync("pos")
			} else {
				uni.removeStorageSync("pos")
			}
			if (res.data.is_bind != 0) {
				if (uni.getStorageSync("sid") && !res.data.userInfo.is_checked) {
					uni.redirectTo({
						url: "/pages/center/accountSet/certification/certification?codeback=true"
					})
				} else if (uni.getStorageSync("sid") && res.data.userInfo.is_checked) {
					channelBindSeller({
						seller_id: uni.getStorageSync("sid")
					}).then(res => {
						if (res.data) {
							uni.removeStorageSync("sid")
							uni.showModal({
								content: res.msg,
								showCancel: false,
								success(re) {
									if (re.confirm) {
										uni.reLaunch({
											url: "/pages/index/index"
										})
									}
								}
							})
						} else {
							uni.removeStorageSync("sid")
							//#ifdef H5
							if (uni.getStorageSync("QRCodeRout")) {
								uni.reLaunch({
									url: uni.getStorageSync("QRCodeRout").split("?")[0]
								})
								uni.removeStorageSync("QRCodeRout")
							} else {
								uni.reLaunch({
									url: "/pages/index/index"
								})
							}
							//#endif
							//#ifndef H5
							uni.navigateBack({})
							//#endif
						}
					})
				} else {
					//#ifdef H5
					if (uni.getStorageSync("QRCodeRout")) {
						uni.reLaunch({
							url: uni.getStorageSync("QRCodeRout")
						})
						uni.removeStorageSync("QRCodeRout")
					} else {
						uni.reLaunch({
							url: "/pages/index/index"
						})
					}
					//#endif
					//#ifndef H5
					uni.navigateBack({})
					//#endif
				}
			} else {
				uni.redirectTo({
					url: "/pages/center/accountSet/phone/addPhone?backurl=login&userType=" + userType
				})
			}
		}
	}
}
